\subsubsection{Virtual methods}

Yet another simple example:

\lstinputlisting[style=customc]{\CURPATH/classes/classes4_virtual.cpp}


Class \IT{object} has a virtual method \TT{dump()} that is being replaced in the inheriting \IT{box} and \IT{sphere} classes.


If we are in an environment where it is not known the type of an object, as in the \main function in example,
where the virtual method \TT{dump()} is called, the information about its type must be stored somewhere, to
be able to call the relevant virtual method.


Let's compile it in MSVC 2008 with the \Ox and \Obzero options and see the code of \main:

\lstinputlisting[style=customasmx86]{\CURPATH/classes/classes4_1.asm}


A pointer to the \TT{dump()} function is taken somewhere from the object.
Where could we store the address of the new method?
Only somewhere in the constructors: there is no other place since nothing else is called in the \main function.
\footnote{You can read more about pointers to functions in the relevant section:(\myref{sec:pointerstofunctions})}


Let's see the code of the constructor of the \IT{box} class:

\lstinputlisting[style=customasmx86]{\CURPATH/classes/classes4_2.asm}


Here we see a slightly different memory layout:
the first field is a pointer to some table
\TT{box::`vftable'} (the name has been set by the MSVC compiler).

\label{RTTI}
\myindex{\Cpp!RTTI}

In this table we see a link to a table named \\
\TT{box::`RTTI Complete Object Locator'} and also a link\\
to the \TT{box::dump()} method.

These are called virtual methods table and \ac{RTTI}.
The table of virtual methods has the addresses of methods and the \ac{RTTI} table contains information about types.

By the way, the \ac{RTTI} tables are used while calling \IT{dynamic\_cast} and \IT{typeid} in \Cpp.
You can also see here the class name as a plain text string.

Thus, a method of the base \IT{object} class may call the virtual method \IT{object::dump()}, which in turn will call
a method of an inherited class, since that information is present right in the object's structure.


Some additional CPU time is needed for doing look-ups in these tables and finding the right virtual method address, 
thus virtual methods are widely considered as slightly slower than common methods.


In GCC-generated code the \ac{RTTI} tables are constructed slightly differently.
% TODO: добавить...
